package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {

        //1.检查手机号和密码
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //1.1 根据手机号 查询用户 是否被禁用
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getStatus, 0)
                    .eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号输入错误");
            }
            //1.2 判断输入密码和数据库是否一致
            String password = apUser.getPassword();
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (!password.equals(md5DigestAsHex)) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码输入错误");
            }
            //1.4 颁发token 封装返回结果 user token
            apUser.setPhone("");
            apUser.setPassword("");
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }else {
            //2.检查设备id 是否存在
            if (dto.getEquipmentId() == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"未发现设备id");
            }
            //2.1 直接颁发token  存id 数据 0
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            //2.2 封装返回结果
            return ResponseResult.okResult(map);
        }
    }
}
